package com.bx.implatform.util;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.node.TextNode;

import java.util.Iterator;
import java.util.Map;

public class ConvertNumbers {

    public static JsonNode convertNumbersToString(JsonNode node) {
        if(node == null){
            return null;
        }
        if (node.isObject()) {
            ObjectNode objectNode = (ObjectNode) node;
            Iterator<Map.Entry<String, JsonNode>> fields = objectNode.fields();

            while (fields.hasNext()) {
                Map.Entry<String, JsonNode> entry = fields.next();
                JsonNode value = entry.getValue();

                if (value.isNumber() && value.canConvertToLong()) {
                    // 替换数字为字符串表示
                    objectNode.put(entry.getKey(), value.asText());
                } else if (value.isObject() || value.isArray()) {
                    // 递归处理嵌套结构
                    convertNumbersToString(value);
                }
            }
        } else if (node.isArray()) {
            ArrayNode arrayNode = (ArrayNode) node;
            for (int i = 0; i < arrayNode.size(); i++) {
                JsonNode element = arrayNode.get(i);
                if (element.isNumber() && element.canConvertToLong()) {
                    arrayNode.set(i, new TextNode(element.asText()));
                } else if (element.isObject() || element.isArray()) {
                    convertNumbersToString(element);
                }
            }
        }
        return node;
    }
}
